--exec SP_CREATE_UPDATE_VENDOR_DETAILS 'SUJAN','SUJAN', '','Finished Goods'
CREATE PROC SP_CREATE_UPDATE_VENDOR_DETAILS
	@VENDORNAME		VARCHAR(50),
	@VENDORNO		VARCHAR(50),
	@CONTACT 		VARCHAR(100),
	@LOCATION_TYPE		VARCHAR(100)
AS
BEGIN
	DECLARE @VENDOR_ID  INT
	DECLARE @ADDRESS_ID  INT
	IF (@VENDORNO IS NOT NULL AND LEN(LTRIM(RTRIM(@VENDORNO))) > 0 )
	 BEGIN	
		SELECT  @VENDOR_ID= VENDOR_ID FROM VENDOR WHERE V_NUMBER= @VENDORNO
	 END
	IF(@VENDOR_ID IS NULL ) 
	 BEGIN
		DECLARE @LOCATION_ADDRESS_ID INT

		INSERT INTO VENDOR ( V_Number, V_Name, V_Added_By_Name, V_Added_By_ID,  V_Is_Deleted, V_Creation_Date, V_Last_Modified_Date )
			    VALUES( @VENDORNO, @VENDORNAME,  'ADMIN', -1, 'N', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)	
		SELECT @VENDOR_ID = @@IDENTITY	

		INSERT INTO ADDRESS ( Address_1, Address_2, City, State, Zipcode, Country, Phone_Number, Fax_Number, Email, Timestamp, Contact_person, Cell_Number)
			   VALUES( '', '', '', '', '', '', '', '','', CURRENT_TIMESTAMP, @CONTACT,'' ) 			
		SELECT @LOCATION_ADDRESS_ID = @@IDENTITY

		INSERT INTO ADDRESS ( Address_1, Address_2, City, State, Zipcode, Country, Phone_Number, Fax_Number, Email, Timestamp, Contact_person, Cell_Number)
			    VALUES( '', '', '', '', '', '', '', '', '', CURRENT_TIMESTAMP, '','') 			
		SELECT @ADDRESS_ID=@@IDENTITY 

		UPDATE VENDOR SET ADDRESS_ID = @ADDRESS_ID WHERE VENDOR_ID = @VENDOR_ID
		--INSERT LOCATIONS...with @LOCATION_ADDRESS_ID
		IF ( @LOCATION_TYPE IS NULL OR @LOCATION_TYPE = 'ALL' )
		 BEGIN
			INSERT INTO Location ( Address_ID, Vendor_ID, L_Contact_Person, L_Type, L_Vendor_Name, L_Is_Deleted, Timestamp)
				SELECT  DISTINCT @LOCATION_ADDRESS_ID, @VENDOR_ID, @CONTACT, BASE_PROCESS_TYPE, @VENDORNAME, 'N', CURRENT_TIMESTAMP FROM PROCESS_TYPES_TABLE 
		 END
		ELSE
		 BEGIN
			INSERT INTO Location ( Address_ID, Vendor_ID, L_Contact_Person, L_Type, L_Vendor_Name, L_Is_Deleted, Timestamp)
				SELECT  DISTINCT @LOCATION_ADDRESS_ID, @VENDOR_ID, @CONTACT, BASE_PROCESS_TYPE, @VENDORNAME, 'N', CURRENT_TIMESTAMP FROM PROCESS_TYPES_TABLE WHERE BASE_PROCESS_TYPE = @LOCATION_TYPE
		 END
	 END
	/*ELSE
	BEGIN
		UPDATE VENDOR SET  V_Sales_Contact= @CONTACT,  V_Last_Modified_Date =CURRENT_TIMESTAMP WHERE VENDOR_ID=@VENDOR_ID 
		SELECT @VENDOR_CODE= @VENDOR_ID
	END*/
END


